import { ComponentOptions, component, data, using } from "@/library/lib";

import { $message } from "@/utils/components-proxy";
import { AdService } from "@/services/AdService";
import { Time } from "@/utils/time";
import { api } from "@/utils/api";
import { logger } from "@/utils/logger";
import { pages } from "@/utils/pages";

/**
 * Page - gift-anim
 * @create 2020-07-16
 * @author Halo
 * @description 砸金蛋提示
 */
@component
export default class GiftAnim extends ComponentOptions {
  // 导出 Component
  @data active: boolean = false;
  @data anim: boolean = false;
  @data callLog: Array<any> = [];
  @data count: number = -1;
  @data max: number = 10;
  @using("AdService") adSerivce: AdService;
  @data cd: number = 3;
  @data timer!: any;
  @data c: number = 0;
  lifetimes = {
    attached() {},
    ready() {
      this.data.timer = setInterval(() => {
        if (this.data.cd > 0) this.setData({ cd: this.data.cd - 1 });
      }, 1000);
    },
    detached() {
      clearInterval(this.data.timer);
    }
  };

  async open() {
    this.setData({ active: true, anim: true, open: Time.now, c: 0 });
    this.update();
  }

  async update() {
    let res = await this.adSerivce.count();
    this.setData({ count: res.count, max: res.cd ? res.cd : 10 });
  }

  close() {
    this.setData({ active: false });
    this.triggerEvent("close");
    this.push();
  }

  async ad() {
    if (this.data.cd) return false;
    await this.update(); // 更新已点击次数
    if (this.data.count < this.data.max) {
      this.triggerEvent("ad", {});
      this.setData({ cd: this.data.max, c: this.data.c + 1 });
    } else {
      $message.msg("您已达到今日砸蛋次数上限,请明日重试！");
    }
  }

  async push() {
    logger.count("gift", {
      in: this.data.open,
      out: new Date().getTime(),
      count: this.data.c
    });
  }
}
